package com.itheima.controller;

import com.itheima.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @RequestMapping("/main")
    public String toMainPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("USER_SESSION");
        if (user != null) {
            model.addAttribute("USER_SESSION", user);
        }
        return "main";
    }

    @RequestMapping("/tologin")
    public String toLoginPage() {
        return "login";
    }

    @RequestMapping("/orderinfo")
    public String orderinfo(HttpSession session, Model model) {
        User user = (User) session.getAttribute("USER_SESSION");
        if (user != null) {
            model.addAttribute("USER_SESSION", user);
        }
        return "orderinfo";
    }

    @RequestMapping("/login")
    public String login(User user, Model model, HttpSession session) {
        String username = user.getUsername();
        String password = user.getPassword();

        System.out.println("用户登录: " + username + ", " + password);

        // 模拟数据库验证
        if (username != null && username.equals("Zhang")
                && password != null && password.equals("123")) {
            session.setAttribute("USER_SESSION", user);
            System.out.println("登录成功");
            return "redirect:main";
        }

        model.addAttribute("msg", "用户名或密码错误，请重新登录！");
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:tologin";
    }
}